import 'package:dio/dio.dart';
import 'package:flutter_bilibili/const/http_const.dart';
import 'package:flutter_bilibili/http/adapter/hi_net_adapter.dart';
import 'package:flutter_bilibili/http/core/hi_error.dart';
import 'package:flutter_bilibili/http/request/base_request.dart';

class DioAdapter extends HiNetAdaptor {
  @override
  Future<HiNetResponse> send<T>(BaseRequest request) async {
    Response? response;
    Options options = Options(headers: request.header);
    var error;

    try {
      if (request.httpMethod() == HttpMethod.GET) {
        // GET请求
        response = await Dio().get(request.url(), options: options);
      } else if (request.httpMethod() == HttpMethod.POST) {
        // POST请求
        response = await Dio()
            .post(request.url(), data: request.params, options: options);
      } else if (request.httpMethod() == HttpMethod.DELETE) {
        // DELETE请求
        response = await Dio()
            .delete(request.url(), data: request.params, options: options);
      }
    } on DioException catch (e) {
      error = e;
      response = e.response;
    }

    if (error != null) {
      throw HiNetError(response?.statusCode ?? -1, error.toString(),
          data: buildRes(response!, request));
    }

    return buildRes(response!, request);
  }
}

/// 返回结果处理
HiNetResponse buildRes(Response response, BaseRequest request) {
  return HiNetResponse(
    data: response.data,
    statusCode: response.statusCode ?? -1,
    request: request,
    statusMessage: response.statusMessage ?? '',
  );
}
